from .celery import app
from ldap3 import Server, Connection, ALL, SUBTREE, ServerPool, ALL_ATTRIBUTES, NTLM, Tls
from apps.account.models import LoonUser
from settings import config
from django.core.cache import cache


@app.task
def ldap_sync_user(ldap_attr):
    dept_dic = {
        'ops': 1,
        'fe': 2,
        'qa': 3,
        'Security': 4,
        'backend': 5,
        'core': 6,
        'app': 7,
        'product': 8,
    }

    conn = Connection(config.MY_LDAP_SERVER_URI, user=config.MY_LDAP_BIND_DN, password=config.MY_LDAP_BIND_PASSWORD,
                      check_names=True, lazy=False, raise_exceptions=False, read_only=False)
    conn.open()
    conn.bind()

    res = conn.search(
        search_base=config.MY_LDAP_SEARCH_BASE,
        # search_filter='(cn=*)',  # 查询所有用户
        search_filter='(objectclass=user)',  # 查询所有用户
        search_scope=SUBTREE,
        attributes=['cn', 'sn', 'givenName', 'mail', 'sAMAccountName', 'distinguishedName']
        # cn用户中文名，sn姓，givenName名，mail邮件，sAMAccountName是账号
    )

    if res:
        for entry in conn.response:
            user = LoonUser
            dict_attr = entry['attributes']
            has_user = user.objects.filter(username=dict_attr['cn']).first()
            user_dept = user.objects.filter(username=has_user).values('dept_id').first()
            dept = dict_attr['distinguishedName'].split(',')[1].split('=')[1]
            email = f"{dict_attr.get('cn')}@bybit.com"

            if dept in dept_dic:
                dept_id = dept_dic.get(dept)
            else:
                dept_id = 100
            # print(dept, email, dept_id)

            if has_user:
                if user_dept['dept_id'] != dept_id:
                    user.objects.filter(username=dict_attr['cn']).update(dept_id=dept_id, email=email)
            else:
                user.objects.create(username=dict_attr['cn'], alias=dict_attr['sn'], email=email, dept_id=dept_id)
